<template>
  <div class="single-page">
    <div class="main-content">
      <div class="search-layout">
        <div class="search-btn">
          <div>
            <a-button type="primary" @click="addRoleFunc">
              <template #icon>
                <PlusOutlined/>
              </template>
              创建角色
            </a-button>
          </div>
        </div>
      </div>
      <div class="table-style">
        <RoleManageTable :columns="columns" :data="dataSource" :isloading="isloading" :pagination="pagination"
                         @tableChange="tableChange" @editFunc="editFunc" @delFunc="delFunc"/>
      </div>
    </div>

    <!-- 创建角色 -->
    <a-modal v-model:visible="addRoleVisiable" title="创建角色" :confirm-loading="addRoleLoading" @ok="addRoleSubmit"
             width='400px'>
      <div style="display:flex; align-items: center">
        <div><span class="font-color_red">*</span><span style="marin-left: 5px">角色名称</span></div>
        <div style="margin-left: 10px">
          <a-input v-model:value="addRoleName" style="width:240px;"/>
        </div>
      </div>
      <div class="margin-top_20" style="display:flex; ">

        <div><span class="font-color_red">*</span><span style="marin-left: 5px">角色描述</span></div>
        <div style="margin-left: 10px">
          <a-textarea v-model:value="addRoleMark" show-count :maxlength="100" allow-clear style="width: 240px"/>
        </div>

      </div>
      <div style="display:flex;">
        <div><span class="font-color_red">*</span><span>角色权限</span></div>
        <!-- 角色权限列表 -->
        <a-tree v-model:selectedKeys="formData.selectedKeys" v-model:checkedKeys="formData.checkedKeys" checkable
                :tree-data="formData.treeifyData" @check="checkChangedFunc">
          <template #title="{ title, key, level }">
            {{ title }} <span style="font-size:12px ;color: #1890ff;">{{ level }}</span>
          </template>
        </a-tree>
      </div>
    </a-modal>

    <!-- 更新角色 -->
    <a-modal title="更新角色" v-model:visible="updateModalVisible" :confirm-loading="updateModalConfirmLoading"
             @ok="updateModalHandleOk" width='400px'>

      <div style="display:flex; align-items: center">
        <div><span class="font-color_red">*</span><span style="marin-left: 5px">角色名称</span></div>
        <div style="margin-left: 10px">
          <a-input v-model:value="updateRoleName" style="width:240px;"/>
        </div>
      </div>
      <div class="margin-top_20" style="display:flex;">
        <div><span class="font-color_red">*</span><span style="marin-left: 5px">角色描述</span></div>
        <div style="margin-left: 10px">
          <a-textarea v-model:value="updateRoleMark" show-count :maxlength="100" allow-clear style="width: 240px"/>
        </div>

      </div>
      <div style="display:flex;">
        <div><span class="font-color_red">*</span><span>角色权限</span></div>
        <!-- 角色权限列表 -->
        <a-tree ref="updateTree" v-model:selectedKeys="formData.selectedKeys" v-model:checkedKeys="formData.checkedKeys"
                checkable
                :tree-data="formData.treeifyData" @check="checkChangedFunc">
          <template #title="{ title, key, level }">
            {{ title }} <span style="font-size:12px ;color: #1890ff;">{{ level }}</span>
          </template>
        </a-tree>
      </div>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
import {cloneDeep} from 'lodash-es';
import type {UnwrapRef} from 'vue';
import {getCurrentInstance, inject, onMounted, reactive, ref} from 'vue';
import type {TableColumnsType} from 'ant-design-vue';
import {message, TreeSelect} from 'ant-design-vue';
import {post} from '@/service/request';

const {proxy, ctx} = getCurrentInstance() as any;
const SHOW_PARENT = TreeSelect.SHOW_PARENT;

const reload: any = inject('reload');
const state = reactive({
  loading: false
});

const pagination = reactive({
  size: "small",
  showSizeChanger: true,
  position: ["bottomCenter"],
  hideOnSinglePage: true,
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: (total: number) => `共${total}条`,
  onShowSizeChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize
  },
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize
  },
});


const columns = ref<TableColumnsType>([
  {
    title: '序号',
    dataIndex: 'sequence',
    key: 'sequence',
    width: 50,
    customRender: ({index}: { index: number }) => {
      return `${(pagination.current - 1) * pagination.pageSize + index + 1}`
    },
    align: 'center'
  },
  {
    title: '角色',
    dataIndex: 'name',
    key: 'name',
    resizable: true,
    width: 200,
    align: 'center'
  },
  {
    title: '描述',
    dataIndex: 'mark',
    key: 'mark',
    resizable: true,
    width: 100,
    align: 'center'
  },
  {
    title: '用户数量',
    dataIndex: 'userCount',
    key: 'userCount',
    resizable: true,
    width: 100,
    align: 'center'
  },
  {
    title: '操作',
    dataIndex: 'operations',
    key: 'operations',
    resizable: true,
    width: 20,
    align: 'center'
  },
]);

interface DataItem {
  id: number,
  key: string;
  sequence: string,
  name: string,
  mark: string,
  userCount: number,
  menuList: any[],
}

const isloading = ref<boolean>(false);
onMounted(() => {
  // 获取角色列表
  getRoleList();
  // 获取权限列表
  getTreeData();
});
const treeifyFunc = (treeData: any, treeList: any[], childList: any[]) => {
  treeData.map((topItem: any) => {
    topItem.key = topItem.id;
    topItem.title = topItem.name;
    topItem.level = topItem.level < 3 ? '菜单' : '按钮';

    if (topItem?.children && topItem?.children.length > 0) {
      treeifyFunc(topItem?.children, treeList, childList);
    } else {
      childList.push(topItem.id);
    }
    treeList.push({
      label: topItem.name,
      value: topItem.id
    })
  })
}
const getTreeData = () => {
  post(`/menu/list`).then((res: any) => {
    if (res.errCode == 0) {
      formData.treeifyData = res.data;
      treeifyFunc(formData.treeifyData, formData.treeList, formData.childList);
    }
  })

}
const dataSource = ref([] as DataItem[]);
const getRoleList = () => {
  post(`/role/list`, {}, {
    current: pagination.current,
    size: pagination.pageSize,
  }).then((res: any) => {
    if (res.errCode == 0) {
      let roleList = [];
      roleList = Object.assign(res.data.records);
      dataSource.value = roleList;
      pagination.total = res.data.total;
    }
  })
}

const tableChange = () => {
  getRoleList()
}

const data: DataItem[] = [];
const editableData: UnwrapRef<Record<string, DataItem>> = reactive({});

const edit = (key: string) => {
  editableData[key] = cloneDeep(dataSource.value.filter(item => key === item.key)[0]);
};
const save = (key: string) => {
  Object.assign(dataSource.value.filter(item => key === item.key)[0], editableData[key]);
  delete editableData[key];
};
// 添加角色相关
const addRoleVisiable = ref<boolean>(false);
const addRoleLoading = ref<boolean>(false);

const modalVisible = ref<boolean>(false);
const modalConfirmLoading = ref<boolean>(false);
// 添加角色弹窗相关
const addRoleName = ref<string>('');
const addRoleMark = ref<string>('');

const addRoleFunc = () => {
  formData.checkedKeys = []
  addRoleVisiable.value = true;
}

const checkAddRule = () => {
  if (addRoleName.value.trim() == '') {
    message.warning('角色名称不能为空');
    return false;
  }
  return true;
}

const formData = reactive({
  checkedResult: [] as any[],
  selectedKeys: [] as any[],
  checkedKeys: [] as any[],
  treeList: [] as any[],
  childList: [] as any[],
  treeifyData: [] as any[],
});

const checkChangedFunc = (checkedKeys: any, e: any) => {
  formData.checkedResult = [...checkedKeys, ...e.halfCheckedKeys];
  console.log('选中的节点', formData.checkedResult);
}
// 菜单列表
const addRoleSubmit = () => {
  // 检查是否为空
  if (checkAddRule()) {
    modalConfirmLoading.value = true;
    const selectMenuList = [] as any[];
    if (formData.checkedResult.length > 0) {
      if (formData.checkedResult.length > 0) {
        formData.checkedResult.forEach((id: any) => {
          formData.treeList.forEach((menu: any) => {
            if (menu.value == id) {
              selectMenuList.push(menu);
            }
          });
        });
      }
    }

    const addRoleParam = {
      name: addRoleName.value,
      mark: addRoleMark.value,
      menuList: selectMenuList
    }
    post(`/role/add`, addRoleParam).then((res: any) => {
      modalConfirmLoading.value = false;
      if (res.errCode == 0) {
        message.success('添加成功');
      } else {
        message.error(res.msg);
      }
      modalVisible.value = false;
      reload();
    });
  }
}

// 删除角色
const delFunc = (id: number) => {
  const delRoleParam = {
    id: id
  }
  post(`/role/delete`, delRoleParam).then((res: any) => {
    if (res.errCode == 0) {
      message.success('删除成功');
    } else {
      message.error(res.msg);
    }
    reload();
  });
};


// 更新角色相关
const updateModalVisible = ref<boolean>(false);
const updateModalConfirmLoading = ref<boolean>(false);
// 更新角色弹窗相关
const updateRoleName = ref<string>('');
const updateRoleMark = ref<string>('');
const updateRoleId = ref<number>();

const editFunc = (record: any) => {
  updateRoleName.value = record.name;
  updateRoleMark.value = record.mark;
  updateRoleId.value = record.id;
  if (record.menuList?.length > 0) {
    record.menuList.forEach((item: any) => {
      formData.childList.forEach((id: any) => {
        if (id == item.value) {
          formData.checkedKeys.push(item.value);
        }
      });
    });
  } else {
    formData.checkedKeys = []
  }
  // 删除父级
  updateModalVisible.value = true;
}

const checkUpdateRule = () => {
  if (updateRoleName.value.trim() == '') {
    message.warning('角色名称不能为空');
    return false;
  }
  return true;
}
const updateModalHandleOk = () => {
  // 检查是否为空
  if (checkUpdateRule()) {
    updateModalConfirmLoading.value = true;
    const updateMenuList = [] as any[];
    if (formData.checkedResult.length > 0) {
      formData.checkedResult.forEach((id: any) => {
        formData.treeList.forEach((menu: any) => {
          if (menu.value == id) {
            updateMenuList.push(menu);
          }
        });
      });
    }
    const updateRoleParam = {
      id: updateRoleId.value,
      name: updateRoleName.value,
      mark: updateRoleMark.value,
      menuList: updateMenuList
    }
    post(`/role/update`, updateRoleParam).then((res: any) => {
      updateModalConfirmLoading.value = false;
      if (res.errCode == 0) {
        message.success('更新成功');
      } else {
        message.error(res.msg);
      }
      updateModalVisible.value = false;
      reload();
    });
  }
}
</script>

<style lang="less" scoped>
.single-page {
  .main-content {
    width: 100%;
    height: 100%;
  }


  .search-layout {
    padding: 30px 10px 10px 5px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .search-content,
  .search-btn {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .table-style {
    margin-top: 20px;
  }
}
</style>
<style lang="less" scoped>
@import "@/style/page.less";
</style>
